package com.bw.module_home.model.Adpter

import android.media.MediaPlayer
import com.bw.lib_storage.db.DBUtils
import com.bw.lib_storage.db.entity.History
import android.net.Uri
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bw.module_home.R
import com.bw.module_home.databinding.HomeVideoBinding
import com.bw.module_home.model.entity.SimpleVideoEntity
import java.util.Date
class HomeVideoApter(val item: List<SimpleVideoEntity>):RecyclerView.Adapter<HomeVideoApter.HomeVideoViewHolder>() {
    // 当前播放的位置
    private var currentPlayingPosition = -1
    // 当前播放的MediaPlayer
    private var currentPlayingMediaPlayer: MediaPlayer? = null
    // 当前播放的SurfaceView
    private var currentPlayingSurfaceView: SurfaceView? = null
    // 用于更新进度条的Handler
    private val progressHandler = android.os.Handler()
    
    class HomeVideoViewHolder(val binding: HomeVideoBinding):RecyclerView.ViewHolder(binding.root) {
        var mediaPlayer: MediaPlayer? = null
        var surfaceView: SurfaceView? = null
        var isPlaying = false
        // 进度条相关
        var isSeeking = false
        // 进度更新Runnable
        var updateProgressRunnable: Runnable? = null
    }
    
    // 格式化时间为MM:SS格式
    private fun formatTime(milliseconds: Int): String {
        val totalSeconds = milliseconds / 1000
        val minutes = totalSeconds / 60
        val seconds = totalSeconds % 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeVideoViewHolder {
        val binding = HomeVideoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return HomeVideoViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return item.size
    }

    override fun onBindViewHolder(holder: HomeVideoViewHolder, position: Int) {
        holder.binding.video = item[position]
        holder.binding.executePendingBindings()

        Glide.with(holder.itemView.context)
            .load(item[position].videomainimag)
            .placeholder(R.drawable.ic_launcher_foreground)
            .error(R.drawable.ic_launcher_foreground)
            .into(holder.binding.videoThumbnail)

        
        // 初始化视频播放相关组件
        initVideoPlayer(holder, position)
        
        // 设置点击事件，用于播放/暂停视频
        holder.binding.root.setOnClickListener {
            toggleVideoPlayback(holder, position)
        }
        
        // 为播放按钮设置单独的点击事件
        holder.binding.playPauseButton.setOnClickListener {
            toggleVideoPlayback(holder, position)
        }
//        Thread.sleep(200*1000)
    }
    
    private fun initVideoPlayer(holder: HomeVideoViewHolder, position: Int) {
        // 如果已经有MediaPlayer，先释放
        releaseMediaPlayer(holder)
        
        // 使用布局中已定义的SurfaceView
        holder.surfaceView = holder.binding.videoSurfaceView
        holder.surfaceView?.visibility = View.INVISIBLE
        
        // 确保缩略图可见
        holder.binding.videoThumbnail.visibility = View.VISIBLE
        // 确保播放按钮可见
        holder.binding.playPauseButton.visibility = View.VISIBLE
        
        // 创建MediaPlayer
        holder.mediaPlayer = MediaPlayer()
        
        // 设置SurfaceHolder.Callback
        holder.surfaceView?.holder?.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holderSurface: SurfaceHolder) {
                // Surface创建后设置给MediaPlayer
                holder.mediaPlayer?.setDisplay(holderSurface)
            }
            
            override fun surfaceChanged(holderSurface: SurfaceHolder, format: Int, width: Int, height: Int) {
                // Surface尺寸改变时的处理
            }
            
            override fun surfaceDestroyed(holderSurface: SurfaceHolder) {
                // Surface销毁时的处理
                holder.mediaPlayer?.setDisplay(null)
            }
        })
        
        try {
            // 设置视频数据源
            val videoUri = Uri.parse(item[position].videopath)
            holder.mediaPlayer?.setDataSource(holder.binding.root.context, videoUri)
            holder.mediaPlayer?.prepareAsync() // 异步准备
            
            // 初始化进度更新Runnable
            holder.updateProgressRunnable = object : Runnable {
                override fun run() {
                    if (holder.isPlaying && !holder.isSeeking && holder.mediaPlayer != null) {
                        val currentPosition = holder.mediaPlayer!!.currentPosition
                        holder.binding.videoSeekBar.progress = currentPosition
                        holder.binding.currentTimeText.text = formatTime(currentPosition)
                    }
                    // 每100毫秒更新一次进度
                    progressHandler.postDelayed(this, 100)
                }
            }
            
            // 设置准备完成监听
            holder.mediaPlayer?.setOnPreparedListener {mediaPlayer ->
                // 设置视频的最大进度
                holder.binding.videoSeekBar.max = mediaPlayer.duration
                // 更新总时长文本
                holder.binding.totalTimeText.text = formatTime(mediaPlayer.duration)
                
                // 如果当前位置是正在播放的位置，则开始播放
                if (position == currentPlayingPosition) {
                    startVideoPlayback(holder)
                }
            }
            
            // 设置进度条拖动开始监听
            holder.binding.videoSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    // 拖动过程中更新当前时间文本
                    if (fromUser) {
                        holder.binding.currentTimeText.text = formatTime(progress)
                    }
                }
                
                override fun onStartTrackingTouch(seekBar: SeekBar) {
                    holder.isSeeking = true
                }
                
                override fun onStopTrackingTouch(seekBar: SeekBar) {
                    holder.isSeeking = false
                    // 拖动结束后跳转到对应位置
                    holder.mediaPlayer?.seekTo(seekBar.progress)
                }
            })
            
            // 设置播放完成监听
            holder.mediaPlayer?.setOnCompletionListener {
                // 播放完成后重置状态
                holder.isPlaying = false
                holder.surfaceView?.visibility = View.INVISIBLE
                holder.binding.videoThumbnail.visibility = View.VISIBLE
                holder.binding.playPauseButton.setImageResource(android.R.drawable.ic_media_play)
                holder.binding.playPauseButton.visibility = View.VISIBLE
                // 重置进度条和时间文本
                holder.binding.videoSeekBar.progress = 0
                holder.binding.currentTimeText.text = "00:00"
                holder.binding.videoSeekBar.visibility = View.INVISIBLE
                holder.binding.currentTimeText.visibility = View.INVISIBLE
                holder.binding.totalTimeText.visibility = View.INVISIBLE
                
                // 停止进度条更新
                holder.updateProgressRunnable?.let {
                    progressHandler.removeCallbacks(it)
                }
                
                if (position == currentPlayingPosition) {
                    resetCurrentPlaybackState()
                }
            }
            
        } catch (e: Exception) {
            e.printStackTrace()
        }

//        Thread.sleep(29000)
    }
    
    private fun toggleVideoPlayback(holder: HomeVideoViewHolder, position: Int) {
        if (holder.isPlaying) {
            // 如果当前视频正在播放，则暂停
            pauseVideoPlayback(holder)
            resetCurrentPlaybackState()
        } else {
            // 如果当前视频没有播放，则先完全停止并释放其他视频
            stopAndReleaseCurrentVideo()
            // 开始播放当前视频
            startVideoPlayback(holder)
            // 保存到历史记录
            saveToHistory(holder, position)
            // 更新当前播放状态
            updateCurrentPlaybackState(holder, position)
        }
    }
    
    private fun startVideoPlayback(holder: HomeVideoViewHolder) {
        holder.mediaPlayer?.start()
        holder.isPlaying = true
        holder.surfaceView?.visibility = View.VISIBLE
        holder.binding.videoThumbnail.visibility = View.INVISIBLE
        holder.binding.playPauseButton.setImageResource(android.R.drawable.ic_media_pause)
        holder.binding.playPauseButton.visibility = View.INVISIBLE // 播放时隐藏按钮
        // 显示进度条和时间文本
        holder.binding.videoSeekBar.visibility = View.VISIBLE
        holder.binding.currentTimeText.visibility = View.VISIBLE
        holder.binding.totalTimeText.visibility = View.VISIBLE
        
        // 开始更新进度条
        holder.updateProgressRunnable?.let {
            progressHandler.removeCallbacks(it)
            progressHandler.postDelayed(it, 0)
        }
    }
    
    private fun pauseVideoPlayback(holder: HomeVideoViewHolder) {
        holder.mediaPlayer?.pause()
        holder.isPlaying = false
        holder.binding.playPauseButton.setImageResource(android.R.drawable.ic_media_play)
        holder.binding.playPauseButton.visibility = View.VISIBLE // 暂停时显示按钮
        // 更新进度条
        holder.mediaPlayer?.let { mp ->
            holder.binding.videoSeekBar.progress = mp.currentPosition
            holder.binding.currentTimeText.text = formatTime(mp.currentPosition)
        }
        
        // 暂停进度条更新
        holder.updateProgressRunnable?.let {
            progressHandler.removeCallbacks(it)
        }
    }
    
    private fun pauseCurrentVideo() {
        // 暂停当前正在播放的视频
        if (currentPlayingMediaPlayer != null && currentPlayingPosition != -1) {
            currentPlayingMediaPlayer?.pause()
            currentPlayingSurfaceView?.visibility = View.INVISIBLE
            
            // 如果能获取到当前播放位置的holder，更新UI状态
            val holder = findViewHolderForAdapterPosition(currentPlayingPosition) as? HomeVideoViewHolder
            holder?.let {
                it.isPlaying = false
                it.binding.videoThumbnail.visibility = View.VISIBLE
                it.binding.playPauseButton.setImageResource(android.R.drawable.ic_media_play)
                it.binding.playPauseButton.visibility = View.VISIBLE
                // 隐藏进度条和时间文本
                it.binding.videoSeekBar.visibility = View.INVISIBLE
                it.binding.currentTimeText.visibility = View.INVISIBLE
                it.binding.totalTimeText.visibility = View.INVISIBLE
                
                // 停止进度条更新
                it.updateProgressRunnable?.let {
                    progressHandler.removeCallbacks(it)
                }
            }
        }
    }
    
    private fun stopAndReleaseCurrentVideo() {
        // 完全停止并重置当前正在播放的视频
        if (currentPlayingMediaPlayer != null && currentPlayingPosition != -1) {
            // 停止播放，添加异常处理
            try {
                try {
                    if (currentPlayingMediaPlayer?.isPlaying == true) {
                        currentPlayingMediaPlayer?.stop()
                    }
                } catch (e: IllegalStateException) {
                    // 捕获isPlaying()或stop()可能抛出的异常
                    e.printStackTrace()
                }
                
                // 重置MediaPlayer到初始状态，准备重新使用
                try {
                    currentPlayingMediaPlayer?.reset()
                } catch (e: IllegalStateException) {
                    // 捕获reset()可能抛出的异常
                    e.printStackTrace()
                }
            } catch (e: Exception) {
                // 捕获其他可能的异常
                e.printStackTrace()
            }
            
            // 尝试重新设置数据源，为下次播放做准备
            try {
                val videoUri = Uri.parse(item[currentPlayingPosition].videopath)
                currentPlayingSurfaceView?.context?.let {
                    currentPlayingMediaPlayer?.setDataSource(
                        it, videoUri)
                }
                currentPlayingMediaPlayer?.prepareAsync()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            
            // 更新UI状态
            currentPlayingSurfaceView?.visibility = View.INVISIBLE
            
            // 如果能获取到当前播放位置的holder，更新UI状态
            val holder = findViewHolderForAdapterPosition(currentPlayingPosition) as? HomeVideoViewHolder
            holder?.let {
                it.isPlaying = false
                it.binding.videoThumbnail.visibility = View.VISIBLE
                it.binding.playPauseButton.setImageResource(android.R.drawable.ic_media_play)
                it.binding.playPauseButton.visibility = View.VISIBLE
            }
        }
        
        // 重置当前播放状态
        resetCurrentPlaybackState()
    }
    
    private fun updateCurrentPlaybackState(holder: HomeVideoViewHolder, position: Int) {
        // 更新当前播放状态
        currentPlayingPosition = position
        currentPlayingMediaPlayer = holder.mediaPlayer
        currentPlayingSurfaceView = holder.surfaceView
    }
    
    private fun resetCurrentPlaybackState() {
        // 重置当前播放状态
        currentPlayingPosition = -1
        currentPlayingMediaPlayer = null
        currentPlayingSurfaceView = null
    }
    
    // 获取当前正在播放的视频位置
    fun getCurrentPlayingPosition(): Int {
        return currentPlayingPosition
    }
    
    // 停止特定位置的视频播放
    fun stopVideoAtPosition(position: Int) {
        if (position == currentPlayingPosition && currentPlayingMediaPlayer != null) {
            // 如果当前位置正是正在播放的位置，则完全停止并重置该视频
            stopAndReleaseCurrentVideo()
        }
    }
    
    private fun releaseMediaPlayer(holder: HomeVideoViewHolder) {
        // 释放MediaPlayer资源，添加异常处理
        try {
            holder.mediaPlayer?.apply {
                try {
                    // 检查MediaPlayer状态并停止播放
                    if (isPlaying) {
                        stop()
                    }
                } catch (e: IllegalStateException) {
                    // 捕获isPlaying()可能抛出的异常
                    e.printStackTrace()
                }
                try {
                    // 释放MediaPlayer资源
                    release()
                } catch (e: IllegalStateException) {
                    // 捕获release()可能抛出的异常
                    e.printStackTrace()
                }
            }
        } catch (e: Exception) {
            // 捕获其他可能的异常
            e.printStackTrace()
        } finally {
            // 确保置空，避免内存泄漏
            holder.mediaPlayer = null
        }
    }
    
    // 释放所有播放器资源
    fun releaseAllPlayers() {
        // 释放当前播放的视频资源，添加异常处理
        try {
            currentPlayingMediaPlayer?.apply {
                try {
                    // 检查MediaPlayer状态并停止播放
                    if (isPlaying) {
                        stop()
                    }
                } catch (e: IllegalStateException) {
                    // 捕获isPlaying()可能抛出的异常
                    e.printStackTrace()
                }
                try {
                    // 释放MediaPlayer资源
                    release()
                } catch (e: IllegalStateException) {
                    // 捕获release()可能抛出的异常
                    e.printStackTrace()
                }
            }
        } catch (e: Exception) {
            // 捕获其他可能的异常
            e.printStackTrace()
        } finally {
            // 确保置空，避免内存泄漏
            currentPlayingMediaPlayer = null
            
            // 停止进度条更新
            progressHandler.removeCallbacksAndMessages(null)
            
            // 重置状态
            resetCurrentPlaybackState()
        }
    }
    
    // 尝试获取指定位置的ViewHolder
    private fun findViewHolderForAdapterPosition(position: Int): RecyclerView.ViewHolder? {
        // 这里简单实现，实际项目中可能需要使用RecyclerView的方法
        // 由于我们无法直接访问RecyclerView实例，这个方法可能无法正常工作
        // 在实际使用中，可能需要通过回调方式获取RecyclerView实例
        return null
    }
    
    // 保存到历史记录
    private fun saveToHistory(holder: HomeVideoViewHolder, position: Int) {
        val videoEntity = item[position]
        
        try {
            val dao = DBUtils.getDB().historyDao()
            
            // 先检查是否已存在相同content的历史记录
            val existingHistory = dao.getHistoryByContent(videoEntity.videopath)
            
            if (existingHistory != null) {
                // 如果存在，更新浏览次数和时间
                dao.incrementViewCount(videoEntity.videopath, Date().time)
                // 同时清理重复的历史记录
                dao.deleteDuplicateHistories()
            } else {
                // 如果不存在，创建新的历史记录
                val history = History(
                    id = 0, // 0表示自动生成
                    title = videoEntity.title ?: "视频标题",
                    content = videoEntity.videopath,
                    image = videoEntity.videomainimag,
                    viewCount = 1,
                    queryTime = Date()
                )
                dao.insert(history)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}